/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.common.aspect;


import cn.hutool.core.collection.CollectionUtil;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CreateCache;
import io.renren.common.annotation.DataFilter;
import io.renren.common.annotation.FlhFilter;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Constant;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysDeptService;
import io.renren.modules.sys.service.SysRoleDeptService;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 数据过滤，切面处理类
 *
 * @author Mark sunlightcs@gmail.com
 */
@Aspect
@Component
public class FlhFilterAspect {

    @Pointcut("@annotation(io.renren.common.annotation.FlhFilter)")
    public void dataFilterCut() {

    }

    @CreateCache(name = "flhCache", cacheType = CacheType.LOCAL, localExpire = 3600, localLimit = 3000)
    private Cache<Integer, List<String>> flhCache;

    @Before("dataFilterCut()")
    public void dataFilter(JoinPoint point) throws Throwable {
        Object params = point.getArgs()[0];
        if (params != null && params instanceof Map) {
            SysUserEntity user = ShiroUtils.getUserEntity();
            //如果不是超级管理员，则进行数据过滤
            if (user.getUserId() != Constant.SUPER_ADMIN) {
                Map map = (Map) params;
                String flh = (String) map.get("flh");
                List<String> flhList = flhCache.get(user.getUserId().intValue());
                if (CollectionUtil.isEmpty(flhList)) {
                    throw new RRException("您没有查询" + flh + "档案的权限");
                }
                boolean hasFlhs = false;
                for (String pflh : flhList) {
                    if (flh.contains(pflh)) {
                        hasFlhs = true;
                    }
                }
                if(!hasFlhs){
                    throw new RRException("您没有查询" + flh + "档案的权限");
                }

            }
            return;
        }
        throw new RRException("参数不全");
    }
}
